******************************************************
global outcomes_slim = " wagez3 pwagez3 " //" wagez3 pwagez3 i_pov3"
global graph_samps = "k1elig fk1elig mk1elig " //"k1elig k2elig""
global graph_predsamps = "predL12"
global graph_ages = "23 26"
global graph_tyrcs = "1979_1991"

global w = 30   //WINDOW SIZE (+/-)
global g = "g" //Use gcollapse?

if "${g}"=="g" ssc install gtools //Efficient collapse tool

use ${clean_data}/taxtax_clean if inrange(z,-${w}-.01,${w}-.01), clear
rename  tyrc_obstyr i_obstaxyr

keep ${outcomes_slim} tyrc_* birth_order* us_born  pob* dob* *age* bg_* male i_obstaxyr z taxyr*


foreach b in 2 {  //Bin Size
	local bins = ""
	capture drop bin_z
	gen bin_z=z-mod(z,`b')+`b'/2
	gen bin_z0=z-mod(z,`b')

	local i = 0
	label define SEQ 0 "BLANK"

	foreach y of global outcomes_slim {
		disp ""
		disp "**************************************"
		disp "**************Y = `y'*****************"
		foreach s1 of global graph_samps {
			disp ""
			disp "***********S1 = `s1'"
			foreach s2 of global graph_ages {
				disp ""
				disp "********S2 = `s2'"
				foreach s3 of global graph_tyrcs {
					disp ""
					disp "********S3 = `s3'"
					foreach s4 in dropany_miss {
						disp ""
						disp "*****S4 = `s4'"
						foreach s5 of global graph_predsamps {
							disp ""
							disp "*S5 = `s5'"
							local i = `i'+1
							label define SEQ `i' "`s1' `s2' `s3' `s4' `s5' `y' ", add
							disp "`i' --- `s1' `s2' `s3' `s4' `s5' `y' "
							qui gen y_`i' = `y' ///
								if ${tyrcs_`s3'} ///
									${r_`s1'} ///
									${a_`s2'} ///
									${sc_`s4'} ///
									${rp_`s5'}

							qui gen n_`i' = 1 ///
										if ${tyrcs_`s3'} ///
											${r_`s1'} ///
											${a_`s2'} ///
											${sc_`s4'} ///
											${rp_`s5'}
						}
					}
				}
			}
		}
	}
}

${g}collapse (mean) y_* (sum) n_* , by(bin_z bin_z0)
reshape long y_ n_ , i(bin_z) j(seqcode)

label values seqcode SEQ
decode seqcode , gen(seq)
*tab seq, m
split seq, gen(s)

rename s6 outcome
rename y_ mean
rename n_ obs
label values seqcode
format seqcode %9.0g

order outcome s1-s5 bin_z0 mean obs seqcode seq
rename s1 sample
rename s2 ages
rename s3 taxyrcuts
rename s4 sch_cuts
rename s5 predsamps

sort seqcode bin_z0

**********************************
**********DIAGNOSTICS:
list outcome sample ages predsamps if bin_z0==0

tab outcome sample, m
tab outcome predsamps, m
summ obs, detail
disp "MIN CELL SIZE: ",r(min)
**********************************

save ${results}/mainrd_graph, replace
